/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-  */
/*
 * gtkapkmanager.c
 * Copyright (C) 2014 Weiketing <weikting@gmail.com>
 * 
 * GtkApkManager is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GtkApkManager is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <config.h>
#include "gtkapkmanager.h"

#include <glib/gi18n.h>
#include <sys/types.h>



/* For testing propose use the local (not installed) ui file */
/* #define UI_FILE PACKAGE_DATA_DIR"/ui/gtkapkmanager.ui" */
/*#define UI_FILE "src/gtkapkmanager.ui"
#define TOP_WINDOW "window"
*/

G_DEFINE_TYPE (Gtkapkmanager, gtkapkmanager, GTK_TYPE_APPLICATION);

/* ANJUTA: Macro GTKAPKMANAGER_APPLICATION gets Gtkapkmanager - DO NOT REMOVE */
struct _GtkapkmanagerPrivate
{
	/* ANJUTA: Widgets declaration for gtkapkmanager.ui - DO NOT REMOVE */
	int r;
};

static char       **remaining_args;

static const GOptionEntry options[] = {
	{ G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_STRING_ARRAY, &remaining_args,
	  NULL,
	  NULL },

	{ NULL }
};

static void
gtkapkmanager_new_window (GApplication *app,
                           const gchar        *file)
{
	//g_warning("file:%s",file);
	window_wrapper_new_window(app,file);
}

/* GApplication implementation */
static void
gtkapkmanager_activate (GApplication *application)
{
	gtkapkmanager_new_window (application, NULL);
}

static void
gtkapkmanager_open (GApplication  *application,
                     GFile        **files,
                     gint           n_files,
                     const gchar   *hint)
{
	gint i;

	for (i = 0; i < n_files; i++){
		gchar *f  = g_file_get_path (files[i]);
		//g_warning("f:%s",f);
		gtkapkmanager_new_window (application, f);
		g_free(f);
	}
}

static void
gtkapkmanager_init (Gtkapkmanager *object)
{
	object->priv = G_TYPE_INSTANCE_GET_PRIVATE (object, GTKAPKMANAGER_TYPE_APPLICATION, GtkapkmanagerPrivate);
}

static void
gtkapkmanager_finalize (GObject *object)
{
	G_OBJECT_CLASS (gtkapkmanager_parent_class)->finalize (object);
}

static GOptionContext *
gtkapkmanager_create_option_context (void)
{
	GOptionContext *context;
	static gsize    initialized = FALSE;

	context = g_option_context_new (N_("- apk files"));
	g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
	g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE);
	g_option_context_set_ignore_unknown_options (context, TRUE);

	if (g_once_init_enter (&initialized)) {
		g_option_context_add_group (context, gtk_get_option_group (TRUE));
		g_once_init_leave (&initialized, TRUE);
	}

	return context;
}

static int
gtkapkmanager_command_line (GApplication            *application,
                             GApplicationCommandLine *command_line)
{
	char           **argv;
	int              argc;
	GOptionContext  *context;
	GError		*error = NULL;

	argv = g_application_command_line_get_arguments (command_line, &argc);

//	g_warning("gtkapkmanager_command_line:%s",argv[0]);
    context = gtkapkmanager_create_option_context ();
	if (! g_option_context_parse (context, &argc, &argv, &error)) {
		g_critical ("Failed to parse arguments: %s", error->message);
		g_error_free (error);
		g_option_context_free (context);

		return -1;
	}

	if(remaining_args!=NULL){
		int i=0;
		for(;remaining_args[i] && remaining_args[i][0];i++){
			const gchar *f=remaining_args[i];
			//g_warning("f:%s",f);
			if(g_file_test (f,G_FILE_TEST_EXISTS) && (g_str_has_suffix (f,".apk") || g_str_has_suffix (f,".APK"))){
				window_wrapper_new_window(application,f);
			}
		}
	}
	
	g_option_context_free (context);
	gdk_notify_startup_complete ();
	remaining_args  = NULL;
	return 0;
}

static void
activate_about (GSimpleAction *action,
		GVariant      *parameter,
		gpointer       user_data)
{
	GApplication *application = user_data;
	GList        *windows;
	GtkWindow *window = NULL;//gtk_application_get_active_window(application);

	if(window == NULL) {
		windows = gtk_application_get_windows (GTK_APPLICATION (application));
		if (windows != NULL){
			window = GTK_WINDOW(windows->data);
		}
	}
	
	static const gchar *authors[]={"wkt<weikting@gmail.com>",NULL};
	gtk_show_about_dialog(window,
		"authors",authors,
	    "copyright","Copyright (c) wkt",
	    "logo-icon-name","apkmanager",
	    "version",VERSION,
	    "website","http://xx51.net/jump/apkmanager.index",
	    "license-type",GTK_LICENSE_GPL_2_0,
	    "program-name","GtkApkManager",
	    NULL);
}


static gboolean
send_delete_event (gpointer data)
{
  GtkWidget *window = data;

  GdkEvent *event;

  event = gdk_event_new (GDK_DELETE);

  event->any.window = g_object_ref (gtk_widget_get_window (window));
  event->any.send_event = TRUE;

  gtk_main_do_event (event);
  gdk_event_free (event);

  return G_SOURCE_REMOVE;
}

static void
activate_quit (GSimpleAction *action,
               GVariant      *parameter,
               GApplication *application)
{

	GList        *windows;
	windows = gtk_application_get_windows (GTK_APPLICATION (application));
	if (windows != NULL){
		GList *l = windows;
		for(;l;l=l->next){
			///g_signal_emit_by_name(l->data,"delete-event",G_TYPE_BOOLEAN,e);
			gdk_threads_add_idle (send_delete_event, l->data);
			///gtk_window_close(GTK_WINDOW(l->data));
		}
	}else{
		g_application_quit (application);
	}
	
}

static const GActionEntry app_menu_entries[] = {
	{ "about", activate_about },
	{ "quit",  activate_quit }
};

static void
gtkapkmanager_starup(GApplication *application)
{

	G_APPLICATION_CLASS (gtkapkmanager_parent_class)->startup (application);

	GtkBuilder *builder;

	g_action_map_add_action_entries (G_ACTION_MAP (application),
					 app_menu_entries,
					 G_N_ELEMENTS (app_menu_entries),
					 application);

	builder = gtk_builder_new ();
	gtk_builder_add_from_string(builder,
		"<interface>"
		"  <menu id='app-menu'>"
		" <section> "
		"  <item> "
		"    <attribute name='action'>app.about</attribute> "
		"    <attribute name='label' translatable='yes'>_About</attribute>"
		"  </item> "
		" </section> "
		" <section> "
		"  <item> "
		"    <attribute name='action'>app.quit</attribute> "
		"    <attribute name='label' translatable='yes'>_Quit</attribute>"
		"  </item> "
		" </section> "
		" </menu> "
		"</interface>",-1,NULL);
		GMenuModel *mm = G_MENU_MODEL (gtk_builder_get_object (builder, "app-menu"));

		gtk_application_set_app_menu (GTK_APPLICATION (application),
						  mm);
		g_object_unref (builder);

}

static void
gtkapkmanager_class_init (GtkapkmanagerClass *klass)
{
	G_APPLICATION_CLASS (klass)->activate = gtkapkmanager_activate;
	G_APPLICATION_CLASS (klass)->open = gtkapkmanager_open;
	G_APPLICATION_CLASS (klass)->command_line = gtkapkmanager_command_line;
	G_APPLICATION_CLASS (klass)->startup = gtkapkmanager_starup;

	g_type_class_add_private (klass, sizeof (GtkapkmanagerPrivate));

	G_OBJECT_CLASS (klass)->finalize = gtkapkmanager_finalize;
}

Gtkapkmanager *
gtkapkmanager_new (void)
{
	g_type_init ();

	return g_object_new (gtkapkmanager_get_type (),
	                     "application-id", "org.gnome.gtkapkmanager",
	                     "flags", G_APPLICATION_HANDLES_OPEN,
	                     NULL);
}

